<template>
  <a-modal
    :title="`APP分类${model?'编辑':'新增'}`"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel');form.resetFields() }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <a-form-item v-show="false" label="主键ID">
          <a-input v-decorator="['id']" disabled />
        </a-form-item>
        <a-form-item label="名称">
          <a-input v-decorator="['name']" placeholder="请填写名称"/>
        </a-form-item>
        <a-row>
          <a-col :span="8">
            <a-form-item label="图片" style="margin-bottom:0" :labelCol="{span:9}" :wrapperCol="{span:15}">
              <d-upload
                v-decorator="['img_url',{initialValue:''}]"
              >
              </d-upload>
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="月份">
          <a-select v-decorator="['month']" placeholder="请选择月份" mode="multiple">
            <a-select-option :value="item.toString()" v-for="item in 12" :key="item">{{ item + '月' }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
// 表单字段
const fields = ['name', 'id', 'img_url', 'month']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 21 }
      }
    }
    return {
      form: this.$form.createForm(this),
      loadingImg: false
    }
  },
  created () {
    console.log('custom modal created')
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      if (this.model) {
        this.form.setFieldsValue(pick(this.model, fields))
      } else {
        this.form.resetFields()
      }
    })
  },
  methods: {
    normFile (e) {
      console.log('Upload event:', e)
      if (e.file.status === 'uploading') {
        this.loadingImg = true
        return
      }
      if (e.file.status === 'done') {
          this.loadingImg = false
      }
      if (Array.isArray(e)) {
        return e
      }
      return e && e.file.response.data.img
    }
  }
}
</script>
